package test4;

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

public class BlockingQueue {
    public static void main(String[] args) {

        ArrayBlockingQueue<String> blockingQueue = new ArrayBlockingQueue<String>(3);

        new Thread(() -> {
            while (true){
                try {
                    blockingQueue.put("面包");
                    System.out.println(Thread.currentThread().getName() + "做好了一个面包");
                    TimeUnit.SECONDS.sleep(new Random().nextInt(3) + 1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "面包师").start();

        new Thread(() -> {
            while (true) {
                try {
                    String bread = blockingQueue.take();
                    System.out.println(Thread.currentThread().getName() + "试吃了一个" + bread);
                    TimeUnit.SECONDS.sleep(new Random().nextInt(3) + 1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "试吃员").start();

    }
}
